<template>
  <div class="channel-edit">
    <van-cell :border="false">
      <div slot="title" class="title-text">我的频道</div>
      <van-button plain class="edit-btn" @click="isEdit=!isEdit" round size="mini" type="danger"
        >{{isEdit ? '完成':'编辑'}}</van-button
      >
    </van-cell>
    <van-grid class="my-grid" :gutter="10">
      <van-grid-item
        v-for="(item, index) in myChannels"
        :key="index"
        class="grid-item"
        @click="onMyChannelClick(item,index)"
      >
        <van-icon v-show="isEdit && !fixedChannels.includes(index)" slot="icon" name="clear"></van-icon>
        <span slot="text" :class="index === active ? 'text active' : 'text'">
            {{item.name}}
        </span>
      </van-grid-item>
    </van-grid>

    <!--频道推荐  -->
    <van-cell :border="false">
      <div slot="title" class="title-text">频道推荐</div>
    </van-cell>
    <van-grid class="recommend-grid" :gutter="10">
      <van-grid-item
        class="grid-item"
        icon="plus"
        v-for="(item, index) in recommendChannels"
        :key="index"
        :text="item.name"
         @click="onAddChannel(item)"
      />
    </van-grid>
  </div>
</template>
<script>
import { GetAllChannels,AddUserChannel,DeleteUserChannel } from "@/api/channel";
import { mapState } from "vuex"
import { setItem } from "@/utils/storage"
export default {
  data() {
    return {
      allChannels: [], // 所有频道
      isEdit:false,   // 控制编辑状态
      fixedChannels:[0]  // 固定频道，不允许删除
    };
  },
  props: {
    myChannels: {
      type: Array,
      required: true,
    },
    active: {
      type: Number,
      required: true,
    },
  },
  computed: {
    ...mapState(['user']),
    //   计算属性会观察内侧依赖发生的变化，重新计算
    recommendChannels() {
      return this.allChannels.filter((channel) => {
        return !this.myChannels.find((val) => {
          return val.id === channel.id;
        });
      });
      //   const channels = [];
      //   this.allChannels.forEach(channel => {
      //     // find遍历数组，找到满足条件的的元素项
      //     const ret =  this.myChannels.find(val=>{
      //           return val.id ===channel.id
      //     })
      //     // 如果不存在与我的频道中则收集起来
      //     if(!ret){
      //         channels.push(channel)
      //     }
      //   });
      // //   把计算结果返回
      // return channels
    },
  },
  async mounted() {
    try {
      const { data } = await GetAllChannels();
      this.allChannels = data.data.channels;
    } catch (error) {
      this.$toast.error("数据获取失败");
    }
  },
  methods: {
    //   添加频道
    async onAddChannel(channel) {
        this.myChannels.push(channel)
        // 数据持久化处理
        if(this.user){
            // 已登录，将数据提交给后台
            try {
                await AddUserChannel({ 
                    id:channel.id,  // 频道ID
                    seq:this.myChannels.length  // 序号 ， 数组的长度，序号从1开始
                })
            } catch (error) {
                this.$toast('保存失败，请稍后重试')
            }
        }else{  
            // 未登录，把数据存储在本地
            setItem('TOUTIAO_CHANNELS',this.myChannels)
        }
    },
    // 我的频道被点击
    onMyChannelClick(channel,index){
        // 如果是编辑状态则执行删除频道，如果不是则是切换频道
        if(this.isEdit){
            // 如果是固定频道则不允许删除
            if(this.fixedChannels.includes(index)){
                return;
            }
            // 让激活频道-1
            if(index<=this.active){
                this.$emit('update-active',this.active-1,true)
            }
            this.myChannels.splice(index,1)
            // 处理持久化
            this.deleteChannel(channel);
        }else{
            // 传递给父组件激活下标
            this.$emit('update-active',index,false)
        }
    },
    // 删除频道持久化
    async deleteChannel(channel){
        try {
            if(this.user){
                // 已登录，更新到线上
                await DeleteUserChannel(channel.id)
            }else{
                // 未登录，更新到本地
                setItem('TOUTIAO_CHANNELS',this.myChannels)
            }
        } catch (error) {
            this.$toast('删除失败，稍后重试')
        }
    }
  },
};
// 所有频道  = 我的频道 + 剩余频道
</script>
<style scoped lang="less">
.channel-edit {
  padding: 85px 0;
  .title-text {
    font-size: 32px;
    color: #333;
  }
  .edit-btn {
    width: 104px;
    height: 48px;
    font-size: 26px;
    color: #f85959;
    border: 1px solid #f85959;
  }
  /deep/ .van-grid-item__icon-wrapper{
      position: unset;
  }
  /deep/ .grid-item {
    width: 160px;
    height: 86px;
    .van-grid-item__content {
      white-space: nowrap;
      background-color: #f4f5f6;
      .van-grid-item__text,
      .text {
        font-size: 28px;
        color: #222;
        margin-top: 0;
      }
      .active {
        color: red;
      }
    }
  }
  /deep/ .recommend-grid {
    .van-grid-item__content {
      flex-direction: row;
      .van-icon-plus {
        font-size: 28px;
      }
      .van-grid-item__text {
        margin-right: 6px;
      }
    }
  }
  /deep/ .my-grid {
    .grid-item {
      .van-icon-clear {
        position: absolute;
        right: -5px;
        top: -5px;
        font-size: 15px;
        color: #cacaca;
        z-index: 2;
      }
    }
  }
}
</style>